package alf.mapping.view;

import alf.mapping.core.Factory;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.util.Map;
/**
	Clase de utilidad variada en la capa de prrsentacion.
	Ofrece funciones de utileria y un almacen
	de objetos para permitir el paso de objetos complejos
	entre actividades.
	
	Como en los extras de un intent solo se guardan
	obetos simples, antes de invocar una actividad,
	hacemos push del objeto en el Env, recuperando un 
	token que pasamos a la actividad en el intent.
	La actvidad usa el token para recuperar (pop) el
	objeto del Env.
*/
public class Env {
	private static Env instance = null;
	private static Map mapa = Factory.createMap();
	private long tokenId = 0;
	private TextView statusView = null;
	private Activity currentActivity;
	
	private static final String DEBUG_TAG = "MAZES";
	//SINGLETON
	private Env() {
		super();
	}

	public static Resources getResources() {
		return getInstance().currentActivity.getResources();
	}

	public static Env getInstance() {
		if (instance==null) {
			instance = new Env();
		}
		return instance;
	}
	public static void debug(String s) {
		Log.d(DEBUG_TAG, s);
	}
	public static void error(Throwable t) {
		Log.e(DEBUG_TAG,"Error",t);
	}
	
	public static void registerActivity(Activity a) {
		getInstance().currentActivity = a;
	}
	public static void toast(Context ctx, String msg) {
		Toast  t =Toast.makeText(ctx, msg, Toast.LENGTH_SHORT);
		t.show();
	}
	
	public String push(Object item) {
		tokenId++;
		String token = Long.toString(tokenId);
		mapa.put(token,item);
		return token;
	}
	
	public Object pop(String token) {
		return mapa.get(token);
	}
	
	public Object getService(Class c , Object client){
		Object r = null;
		String name = c.getName();
		debug("Env.getService("+ name + ")");
		if (mapa.containsValue(name)){
			r = mapa.get(name);
		} else {
			r =	Factory.createService(name);
			mapa.put(name,r);
		}
		return r;
	}
	
	public static void setStatus(int msgId,Object... args) {
		String msg = getInstance().currentActivity.getResources().getString(msgId,args);
		setStatus(msg);
	}
	
	public static void setStatus(String msg) {
		getInstance();
		if (instance.statusView!=null){
			instance.statusView.setText(msg);
		} else {
			debug("NO STATUS:"+msg);
		}
	}
	
	public static void registerStatusView(TextView v) {
		getInstance().statusView = v;
	}
	
	public static void confirmDialog(Context ctx, String title,String msg,
		Dialog.OnClickListener listener, Dialog.OnClickListener negativeListener) {
		new AlertDialog.Builder(ctx)
			.setCancelable(true)
			.setTitle(title)
			.setMessage(msg)
			.setNegativeButton(android.R.string.cancel,negativeListener)
			.setPositiveButton(android.R.string.ok,listener)
			.show();
	}
	
	public static void alertDialog(Context ctx, String title, String msg,
			Dialog.OnClickListener listener){
		new AlertDialog.Builder(ctx)
			.setCancelable(false)
			.setTitle(title)
			.setMessage(msg)
			.setPositiveButton(android.R.string.ok,listener)
			.show();
	}
	
	public static void showSelectDialog(Context ctx, String title,
			ListAdapter adapter,
			DialogInterface.OnClickListener listener){
		new AlertDialog.Builder(ctx)
			.setTitle(title)
			.setAdapter(adapter,listener)
			.show();
	}
	
	public static SharedPreferences getPreferences(){
		//SharedPreferences sharedPref = instance.currentActivity.getSharedPreferences("preferences",Context.MODE_PRIVATE);
		SharedPreferences sharedPref =  PreferenceManager.getDefaultSharedPreferences(instance.currentActivity);
		return sharedPref;
	}
	
	public static String getDocumentsDir(){
		String DOCUMENTS = "Documents";
		String path;
		File f = Environment.getExternalStorageDirectory();
		File docs = findSubdir(f,DOCUMENTS);
		if (docs==null){
			// {default}/Documents doesnt exist
			// create it.
			docs = new File(f.getAbsolutePath()+"/"+DOCUMENTS);
			docs.mkdirs();
		}
		path = docs.getAbsolutePath();
		return path;
	}

	private static File findSubdir(File f, String name) {
		for (File subdir: f.listFiles()){
			if (subdir.isDirectory() && subdir.getName().equalsIgnoreCase(name)){
				return subdir;
			}
		}
		return null;
	}

}
